package com.gin.kotlin.no_gay_alliance.worker

import android.content.Context
import android.util.Log
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.gin.kotlin.no_gay_alliance.app.App
import java.util.concurrent.TimeUnit

/**
 * 定时更新回复历史计数
 * @constructor
 */
class ReplyHistoryCountWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        val replyHistoryTopicDao = App.INSTANCE.database.replyHistoryTopicDao()
        val replyHistoryUserDao = App.INSTANCE.database.replyHistoryUserDao()
        val replyHistoryDao = App.INSTANCE.database.replyHistoryDao()

        Log.i(TAG, "按照用户和主题统计回复历史记录数。。。")

        val replyHistoryUsers = replyHistoryUserDao.list()
        if (!replyHistoryUsers.isNullOrEmpty()) {
            val countByUserId = replyHistoryDao.countByUserId(replyHistoryUsers.map { it.userId }.toTypedArray())
            replyHistoryUsers.forEach { u ->
                countByUserId?.firstOrNull { c -> c.id == u.userId }?.also { u.count = it.count }
            }
            replyHistoryUserDao.update(replyHistoryUsers)
            Log.i(TAG, "更新用户回复数:")
            replyHistoryUsers.forEach { Log.i(TAG, "\t${it.username}: ${it.count}") }
        }

        val replyHistoryTopics = replyHistoryTopicDao.list()
        if (!replyHistoryTopics.isNullOrEmpty()) {
            val countByTopicId = replyHistoryDao.countByTopicId(replyHistoryTopics.map { it.topicId }.toTypedArray())
            replyHistoryTopics.forEach { t ->
                countByTopicId?.firstOrNull { c -> c.id == t.topicId }?.also { t.count = it.count }
            }
            replyHistoryTopicDao.update(replyHistoryTopics)
            Log.i(TAG, "更新主题回复数:")
            replyHistoryTopics.forEach { Log.i(TAG, "\t${it.title}: ${it.count}") }
        }

        // 隔5分钟再次更新
        start(5)

        return Result.success()
    }

    companion object {
        private val TAG = ReplyHistoryCountWorker::class.java.simpleName
        fun start(delayMinutes: Long = 0) {
            val manager = WorkManager.getInstance(App.INSTANCE)
            // 清空相同任务
            manager.cancelAllWorkByTag(ReplyHistoryCountWorker::class.java.name)
            // 构造任务请求
            val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.NOT_REQUIRED).build()
            // 一次性任务
            val workRequest = OneTimeWorkRequest.Builder(ReplyHistoryCountWorker::class.java)
                .setConstraints(constraints)
                // 执行延迟
                .setInitialDelay(delayMinutes, TimeUnit.MINUTES)
                // 重试策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                .build()
            // 提交任务
            manager.enqueue(workRequest)
        }
    }
}